//
//  ZFAMapManager.swift
//  map
//
//  Created by fyzq on 2024/2/4.
//

import UIKit
import RxSwift
class ZFAMapManager: NSObject {
    private var locationManager:AMapLocationManager!
    static let shared = ZFAMapManager()
    private var subject = PublishSubject<AMapReGeocode>()
    private  var request:AMapSearchAPI!
    private override init(){
        super.init()
        setDefaultConfig()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setDefaultConfig(){
        AMapServices.shared().apiKey = "ded5ae99f594fc462fe5fb13580a309d"
        AMapServices.shared().enableHTTPS = true
        
        AMapLocationManager.updatePrivacyAgree(AMapPrivacyAgreeStatus.didAgree)
        AMapLocationManager.updatePrivacyShow(AMapPrivacyShowStatus.didShow, privacyInfo: AMapPrivacyInfoStatus.didContain)
        
        locationManager = AMapLocationManager.init()
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.distanceFilter = 10.0
        
        request = AMapSearchAPI()
        request?.delegate = self

    }
    
    static func requestLocation()->Observable<CLLocation>{
        
        return Observable.create { observer in
            ZFAMapManager.shared.locationManager.desiredAccuracy = kCLLocationAccuracyKilometer
            ZFAMapManager.shared.locationManager.requestLocation(withReGeocode: false) { location, geo, e in
                if(e == nil){
                    guard let location = location else {
                        return
                    }
                    observer.onNext(location)
                }
            }
            return Disposables.create()
        }
       
    }
    func onReGeocodeSearch(location:CLLocationCoordinate2D)->PublishSubject<AMapReGeocode>{
        let regeo = AMapReGeocodeSearchRequest()
        regeo.location = AMapGeoPoint.location(withLatitude: location.latitude, longitude: location.longitude)
        regeo.requireExtension = true
        request!.aMapReGoecodeSearch(regeo)
        return self.subject
    }

    
}

extension ZFAMapManager:AMapSearchDelegate {
    func onReGeocodeSearchDone(_ request: AMapReGeocodeSearchRequest!, response: AMapReGeocodeSearchResponse!) {
        if response.regeocode != nil{
            self.subject.onNext(response.regeocode)
        }
    }
    func aMapSearchRequest(_ request: Any!, didFailWithError error: Error!) {
        print("失败")
    }
}
